package logic

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"time"
	"video-manager/model/cache"
	"video-manager/model/mysql"

	"video-manager/usersrpc/internal/svc"
	"video-manager/usersrpc/usersrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type VideoShowLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewVideoShowLogic(ctx context.Context, svcCtx *svc.ServiceContext) *VideoShowLogic {
	return &VideoShowLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *VideoShowLogic) VideoShow(in *usersrpc.VideoShowRequest) (*usersrpc.VideoShowResponse, error) {
	// todo: add your logic here and delete this line
	var findUser mysql.User
	if err := findUser.FindUserByUserId(mysql.DB, in.UserId); err != nil {
		return nil, err
	}
	if findUser.ID == 0 {
		return nil, errors.New("用户不存在")
	}
	key := fmt.Sprintf("show_%s", in.UserId)
	result, _ := cache.Rdb.Get(l.ctx, key).Result()

	var findVideo mysql.Video
	var list []*usersrpc.TopicList
	if err := findVideo.FindVideoByVid(mysql.DB, in.VideoId); err != nil {
		return nil, err
	}
	if findVideo.ID == 0 {
		return nil, errors.New("视频不存在")
	}
	show := mysql.VideoShow(mysql.DB, in.VideoId)
	if result == "" {
		list = mysql.TopicList(mysql.DB, list)
		marshal, _ := json.Marshal(&list)
		cache.Rdb.Set(l.ctx, key, marshal, time.Minute*10)
	} else {
		json.Unmarshal([]byte(result), &list)
	}

	return &usersrpc.VideoShowResponse{
		VideoId:       show.VideoId,
		VideoTitle:    show.VideoTitle,
		VideoCategory: show.VideoCategory,
		VideoLink:     show.VideoLink,
		CoverLink:     show.CoverLink,
		VideoIntro:    show.VideoIntro,
		PlayNum:       show.PlayNum,
		LikeNum:       show.LikeNum,
		CollectNum:    show.CollectNum,
		CommentNum:    show.CommentNum,
		ReleaseTime:   show.ReleaseTime,
		VideoStatus:   show.VideoStatus,
		TopicName:     show.TopicName,
		NickName:      show.NickName,
		AvatarLink:    show.AvatarLink,
		Lists:         list,
	}, nil
}
